#install.packages("ISwR")
library(ISwR)
# hace varios calculos muy simples y plots basicos, etc. no aporia nada hacerlo aqui
# construimos un vector

# 1.1.3 Vectorized arithmetic ---------------------------------------------


weight <- c(60, 72, 57, 90, 95, 72)
height <- c(1.75, 1.80, 1.65, 1.90, 1.74, 1.91)
bmi <- weight/height^2
# vamos a calcular la desviacion standard de weight a mano
weight.mean <- sum(weight)/length(weight)
weight.sd <- sqrt(sum((weight-weight.mean)^2)/(length(weight)-1))
# comparamos con la calculada por R
if(round(weight.sd,5)-sd(weight) < 1e-5) print("Las varianzas son iguales")

# 1.1.4 Standard procedures -----------------------------------------------


# veamos un ejemplo de t.test aunque se explicara en el chapter 5
t.test(bmi, mu=22.5)
# The p-value is not small, indicating that it is not at all unlikely
# to get data like those observed if the mean were in fact 22.5.

# 1.1.5 Graphics ----------------------------------------------------------


plot(height,weight)
plot(height, weight, pch=2) # con triangulos es lugar de circulos
# los valores ideales serian (con un bmi medio de 22.5)
hh <- c(1.65, 1.70, 1.75, 1.80, 1.85, 1.90)
lines(hh, 22.5 * hh^2)

# 1.2.2 Functions and arguments -------------------------------------------


args(plot.default) # vemos los argumentos de una funcion

# 1.2.3 Vectors  ----------------------------------------------------------


c("Huey","Dewey","Louie")
c('Huey','Dewey','Louie')
c(T,T,F,T)
# la comparacion de vectores da un vector de booleans
bmi > 25

# 1.2.4 Quoting and escape sequences --------------------------------------


cat(c("Huey","Dewey","Louie"))
cat("Huey","Dewey","Louie", "\n")
# para escapar las comillas dobles se usa la barra invertida
# por eso, to put a backslash in a string, you must double it.
cat("What is \"R\"?\n")

# 1.2.6 Functions that create vectors -------------------------------------


# es posible asignar nombres a los elementos de un vector
x <- c(red="Huey", blue="Dewey", green="Louie")
seq(4,9)
seq(4,10,2)
seq(1.65,1.90,0.05)

oops <- c(7,9,13)
rep(oops,3)
rep(oops,1:3)
rep(1:2,c(10,15)) # repetimos 1 10 veces y 2 15

# 1.2.7 Matrices and arrays -----------------------------------------------


## veamos varias formas de crear matrices:
x <- 1:12
dim(x) <- c(3,4)
x
# otra forma de conseguir esto mismo:
matrix(1:12,nrow=3,byrow=F)
rownames(x) <- LETTERS[1:3] # asignamos nombres a las filas
x

x.t <- t(x) # trasponemos la matriz
x.t
  
cbind(A=1:4,B=5:8,C=9:12)
rbind(A=1:4,B=5:8,C=9:12)

# 1.2.8 Factors -----------------------------------------------------------


pain <- c(0,3,2,2,1)
fpain <- factor(pain,levels=0:3)
levels(fpain) <- c("none","mild","medium","severe")
fpain
as.numeric(fpain) ## esta NO ES LA NUMERACION ORIGINAL
levels(fpain)
# es posible crear factores ordenados pero por ahora es mejor no meternos ahí

# 1.2.9 Lists -------------------------------------------------------------

intake.pre <- c(5260,5470,5640,6180,6390,6515,6805,7515,7515,8230,8770)
intake.post <- c(3910,4220,3885,5160,5645,4680,5265,5975,6790,6900,7335)
mylist <- list(before=intake.pre,after=intake.post)
mylist
mylist$before

# 1.2.10 Data frames ------------------------------------------------------

d <- data.frame(intake.pre,intake.post) # coje los vectores como columnas
d
d$intake.pre

# 1.2.11 Indexing ---------------------------------------------------------

intake.pre[5]
intake.pre[5] <- 6390
intake.pre[c(3,5,7)] #it is necessary to use the c(...) ya que intake.pre[3,5,7] es para un array multidimensional
intake.pre[1:5]
intake.pre[-c(3,5,7)] # se muestran todos EXCEPTO los que se indiquen

# 1.2.12 Conditional selection --------------------------------------------

intake.post[intake.pre > 7000]
# los operadores logicos son & (logical “and”), | (logical “or”), and ! (logical “not”)
intake.pre > 7000 & intake.pre <= 8000 #devuelve un vector de booleans
# Notice that there is a real need for is.na because you cannot make comparisons of the form x==NA.

# 1.2.13 Indexing of data frames ------------------------------------------

d <- data.frame(intake.pre,intake.post)
d[5,1] # devuelve un elemento
d[5,] # devuelve una fila
d[,2] # devuelve una columna
d[d$intake.pre>7000,] # todas las filas cuyo inteake.pre sea > 7000
d[1:2,] # vemos las primeras filas
head(d) # por defecto se muestran las 6 primeras filas
tail(d) # por defecto se muestran las 6 ultimas filas

# 1.2.14 Grouped data and data frames -------------------------------------

energy
exp.lean <- energy$expend[energy$stature=="lean"] # nos quedamos con el subset de expends que tiene estatura lean
exp.obese <- energy$expend[energy$stature=="obese"] # nos quedamos con el subset de expends que tiene estatura obese
# otra forma mejor de hacerlo:
l <- split(energy$expend, energy$stature)
l

# 1.2.15 Implicit loops ---------------------------------------------------
head(thuesen)
lapply(thuesen, mean, na.rm=T)
sapply(thuesen, mean, na.rm=T)

replicate(10,mean(rexp(20))) # repetir 10 veces el experimento y guardar los resultados en un vector
#para tratae con matrices:
m <- matrix(rnorm(12),4)
m
apply(m, 2, min) # el 2 indica que tratamos con columnas, 1 serian las filas
tapply(energy$expend, energy$stature, median) # para tratar con factores y agrupaciones

# 1.2.16 Sorting ----------------------------------------------------------

# para ordenar un vector:
intake$post
sort(intake$post)
# para ordenar un dataframe segun los valores de una columna:
d[order(intake$post),]

# Sorting by several criteria is done simply by having several arguments to
# order; for instance, order(sex,age) will give a main division into men
# and women, and within each sex an ordering by age. The second variable
# is used when the order cannot be decided from the first variable. Sorting
# in reverse order can be handled by, for example, changing the sign of the
# variable.


# 1.3 EXERCICES -----------------------------------------------------------

# 1.1 How would you check whether two vectors are the same if they
# may contain missing (NA) values? (Use of the identical function is considered cheating!)
c1 <- c(1,2,3,4,NA,6,7,8,9,0) 
c2 <- c(1,2,3,4,NA,6,7,8,9,0) 
c3 <- c(0,9,8,7,6,5,NA,3,2,1)
c4 <- c(1,2,3,4,5,6,7,8,9,NA) 

compare <- function (x, y){
  all(is.na(x) == is.na(y)) & all((x == y)[!is.na(x)])
}
compare(c1,c2)
compare(c1,c3)
compare(c1,c4)

# 1.2 If x is a factor with n levels and y is a length n vector, what happens
# if you compute y[x]?
x <- c(0,0,1,1,0,1)
x.f <- as.factor(x)
y <- c(10,11)
y[x.f]

x <- factor(c("Huey", "Dewey", "Louie", "Huey"))
y <- c("blue", "red", "green")
x
y[x]

# 1.3 Write the logical expression to use to extract girls between 7 and 14
# years of age in the juul data set.
head(juul)
juul.c <- juul[!is.na(juul$age),]
teens <- juul.c[juul.c$age >=7 & juul.c$age <=14 & juul.c$sex ==2,]
summary(teens)

# 1.4 What happens if you change the levels of a factor (with levels) and
# give the same value to two or more levels?
x <- factor(c("Huey", "Dewey", "Louie", "Huey"))
levels(x) <- c("Huey", "Dewey","Dewey")
x

# 1.5 On p. 27, replicate was used to simulate the distribution of the
# mean of 20 random numbers from the exponential distribution by repeating
# the operation 10 times. How would you do the same thing with
# sapply?
set.seed(1234)
r1 <- replicate (10, mean(rexp(20)))
r1

set.seed(1234)
m <- rep(20, 10)
df <- as.data.frame(sapply(m,rexp))
r2 <- sapply(df, mean)
r2
compare(r1,r2)

#una forma MUCHO mejor

set.seed(1234)
r3 <- sapply(1:10, function(i){mean(rexp(20))})
r3
compare(r1,r3)


